<script setup>
import { ref, onMounted, getCurrentInstance, reactive, nextTick } from "vue";
import utils from "../utils/utils";
const { proxy } = getCurrentInstance();
//查询列表
const queryForm = ref({
  roleName: "",
});
const showModal = ref(false);
const showPermission = ref(false);
const curRoleName = ref("");
const curRoleId = ref("");
const menuList = ref([]);
const actionMap = ref({});
//列表数据
const roleList = ref([]);
const action = ref("add");
//模态框表单
const roleForm = ref({
  roleName: "",
  remark: "",
});
//表头
const columns = reactive([
  {
    label: "角色名称",
    prop: "roleName",
  },
  {
    label: "备注",
    prop: "remark",
  },
  {
    label: "权限列表",
    prop: "permissionList",
    formatter(row, column, value) {
      let names = [];
      let list = value.halfCheckedKeys || [];
      list.map((key) => {
        if (key) names.push(actionMap.value[key]);
      });
      return names.join(",");
    },
  },
  {
    label: "更新时间",
    prop: "path",
  },
  {
    label: "创建时间",
    prop: "createTime",
    formatter(row, column, value) {
      return utils.formatDate(row.createTime);
    },
  },
]);
//分页
const pager = ref({
  total: 0,
  pageSize: 10,
  pagerNum: 1,
});

//规则
const rules = {
  roleName: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: "blur",
    },
  ],
};
//重置
const handleReset = (form) => {
  proxy.$refs[form].resetFields();
};
//列表渲染
const getRoleList = async () => {
  await proxy.$api
    .getRoleList({ ...queryForm.value, ...pager.value })
    .then((res) => {
      console.log(res);
      roleList.value = res.list;
      pager.value = res.page;
    });
};
//查询
const handleQuery = async () => {
  await getRoleList();
};
//创建
const handleAdd = () => {
  showModal.value = true;
  action.value = "create";
};
//取消
const handleClose = () => {
  showModal.value = false;
  handleReset("dialogForm");
};
//确定
const handleSubmit = () => {
  proxy.$refs.dialogForm.validate(async (valid) => {
    console.log(valid + "------");
    let params = { ...roleForm.value, action: action.value };
    let res = await proxy.$api.roleOperate(params);
    console.log(res);
    if (res) {
      showModal.value = false;
      if (action.value == "add") {
        proxy.$message.success("创建成功");
      } else {
        proxy.$message.success("编辑成功");
      }
      handleReset("dialogForm");
      getRoleList();
    }
  });
};

//编辑
const handleEdit = (row) => {
  console.log(row);
  showModal.value = true;
  action.value = "edit";
  nextTick(() => {
    Object.assign(roleForm.value, {
      _id: row._id,
      remark: row.remark,
      roleName: row.roleName,
      action: action.value,
    });
  });
};
//删除
const handleDelete = async (_id) => {
  let res = await proxy.$api.roleOperate({ _id, action: "delete" });
  if (res) {
    proxy.$message.success("删除成功");
    getRoleList();
  }
};
//权限设置
const handlePermissionCloseDialog = () => {
  showPermission.value = false;
};
const handlePermission = (row) => {
  showPermission.value = true;
  curRoleId.value = row._id;
  curRoleName.value = row.roleName;
  const { checkedKeys } = row.permissionList;
  setTimeout(() => {
    proxy.$refs.permissionTree.setCheckedKeys(checkedKeys);
  });
};
const getMenuList = async () => {
  await proxy.$api.menuList().then((res) => {
    console.log(res);
    menuList.value = res;
    getActionMap(res);
  });
};
//权限提交
const handlePermissionSubmit = async () => {
  let nodes = proxy.$refs.permissionTree.getCheckedNodes();
  let halfKeys = proxy.$refs.permissionTree.getHalfCheckedKeys();
  let checkedKeys = [];
  let parentKeys = [];
  nodes.map((node) => {
    if (!node.children) {
      checkedKeys.push(node._id);
    } else {
      parentKeys.push(node._id);
    }
  });
  let params = {
    _id: curRoleId.value,
    permissionList: {
      checkedKeys,
      halfcheckedKeys: parentKeys.concat(halfKeys),
    },
  };
  await proxy.$api.updatePermission(params).then((res) => {
    if (res) {
      showPermission.value = false;
      proxy.$message.success("权限设置成功");
      getRoleList();
    }
  });
};
const getActionMap = (list) => {
  let Map = ref({});
  const deep = (arr) => {
    while (arr.length) {
      let item = arr.pop();
      if (item.children && item.action) {
        Map[item._id] = item.menuName;
      }
      if (item.children && !item.action) {
        deep(item.children);
      }
    }
  };
  deep(JSON.parse(JSON.stringify(list)));
  
  actionMap.value = Map.value;
  console.log(actionMap.value+'11111111111111111111');
};

const handleCurrentChange = (current) => {
  pager.value.pageNum = current;
  getRoleList();
};
onMounted(() => {
  getRoleList();
  getMenuList();
});
</script>

<template>
  <div class="UserManager">
    <div class="UserManager-top">
      <el-form
        :inline="true"
        :model="queryForm"
        ref="form"
        class="UserManager-form"
      >
        <el-form-item label="菜单名称" prop="roleName">
          <el-input
            v-model="queryForm.roleName"
            placeholder="请输入菜单名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleReset('form')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="UserManager-main">
      <div class="UserManager-main-buttom">
        <el-button type="primary" @click="handleAdd(1)">创建</el-button>
      </div>
      <el-table
        ref="multipleTable"
        :data="roleList"
        tooltip-effect="dark"
        style="width: 100%"
        row-key="_id"
      >
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作" class="btn">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="primary"
              @click="handlePermission(scope.row)"
              >权限设置</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="pager.total"
        class="pagination"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="角色新增"
      v-model="showModal"
      :before-close="handleCloseDialog"
    >
      <el-form
        class="adduser-form"
        :rules="rules"
        ref="dialogForm"
        :model="roleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="roleForm.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :row="2"
            v-model="roleForm.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="权限设置"
      v-model="showPermission"
      :before-close="handlePermissionCloseDialog"
    >
      <el-form class="adduser-form" :model="roleForm">
        <el-form-item label="角色名称" prop="roleName">
          {{ curRoleName }}
        </el-form-item>
        <el-form-item label="选择权限" prop="remark">
          <el-tree
            :data="menuList"
            show-checkbox
            node-key="_id"
            :props="{ label: 'menuName' }"
            default-expand-all
            ref="permissionTree"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPermission = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
* {
  //   padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.UserManager {
  width: 100%;
  height: 100%;
  background-color: #dfdfdf;

  .UserManager-top {
    width: 100%;
    height: 100px;
    background-color: #fff;
    margin-bottom: 20px;
    padding: 20px;
    border-radius: 5px;

    .UserManager-form {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;

      .el-form-item {
        display: flex;
        align-items: center;

        .el-input {
          width: 200px;
          height: 40px;
        }

        .el-select {
          width: 200px;
          height: 40px;

          :deep(.el-select__wrapper) {
            height: 40px;
          }

          :deep(.el-select__selected-item) {
            padding: 10px;
            font-size: 14px;
          }
        }

        .el-button {
          width: 70px;
          height: 40px;
        }
      }
    }
  }

  .UserManager-main {
    width: 100%;
    height: calc(100% - 100px);
    background-color: #fff;

    .UserManager-main-buttom {
      width: 100%;
      height: 80px;
      padding: 20px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ccc;

      .el-button {
        height: 40px;
        color: #fff;
      }

      .el-button:first-of-type {
        width: 70px;
        background-color: #409eff;
      }

      .el-button:last-of-type {
        width: 100px;
        background-color: #f56c6c;
      }
    }

    .pagination {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      padding: 20px;
    }
  }

  :deep(.el-dialog) {
    width: 500px;
    // height: 500px;

    .adduser-form {
      // width: 200px;
      padding: 10px;
      height: 100%;
      display: flex;
      flex-direction: column;

      .el-form-item {
        width: 100%;
        // height: 50px;
        display: flex;
        align-items: start;

        label {
          width: 80px;
        }
      }
    }
  }
  :deep(.cell) {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    button {
      flex: 1;
    }
  }
}
</style>
